import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:toys_flutter/api/app.dart';
import 'package:toys_flutter/components/RefreshableListView.dart';
import 'package:toys_flutter/utils/index.dart';

class MyGift extends StatefulWidget {
  const MyGift({super.key});

  @override
  _MyGiftState createState() => _MyGiftState();
}

class _MyGiftState extends State<MyGift> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  List<dynamic> _followedList = [];
  int page = 1;
  bool isMore = true;
  bool isLoading = false;
  int tabIndex = 0;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        setState(() {
          tabIndex = _tabController.index;
          page = 1;
          isMore = true;
        });
        _fetchData();
      }
    });
    _fetchData();
  }

  Future<void> _fetchData() async {
    setState(() {
      isLoading = true;
    });

    var API = tabIndex == 0 ? Api.toysInGiftList : Api.toysOutGiftList;
    try {
      var res = await API({'page': page});
      if (res['code'] == 1) {
        setState(() {
          if (page == 1) {
            _followedList = res['data']['list'] ?? [];
          } else {
            _followedList = [..._followedList, ...res['data']['list'] ?? []];
          }
          isMore = res['data']['more'] == 0 ? false : true;
        });
      } else {
        _showError('加载失败，请重试');
      }
    } catch (e) {
      _showError('网络错误，请重试');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  Future<void> onLoadMore() async {
    if (!isMore || isLoading) return;
    page++;
    await _fetchData();
  }

  Future<void> _refreshData() async {
    page = 1;
    await _fetchData();
  }

  void _showError(String message) {
    TDToast.showIconText(message,
        icon: TDIcons.error,
        direction: IconTextDirection.vertical,
        context: context);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: const Text('我的礼物'),
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '收到的礼物'),
            Tab(text: '赠送的礼物'),
          ],
          labelColor: Colors.blue,
          unselectedLabelColor: Colors.black,
          dividerColor: Colors.transparent,
        ),
      ),
      body: Column(
        children: [
          Expanded(
            child: RefreshableListView(
              onRefresh: _refreshData,
              onLoadMore: onLoadMore,
              enableLoadMore: true,
              children: [
                ...List.generate(
                  _followedList.length,
                  (index) => ListItem(data: _followedList[index]),
                ),
                if (isLoading)
                  const Padding(
                    padding: EdgeInsets.symmetric(vertical: 20),
                    child: Center(child: CircularProgressIndicator()),
                  ),
                if (!isMore && _followedList.isNotEmpty)
                  const Padding(
                    padding: EdgeInsets.symmetric(vertical: 20),
                    child: TDDivider(
                      text: '没有更多了',
                      alignment: TextAlignment.center,
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class ListItem extends StatelessWidget {
  Map<String, dynamic>? data;

  ListItem({
    required this.data,
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ListTile(
          leading: TDImage(
            width: 60,
            height: 60,
            imgUrl: data!['gift']['image'],
            fit: BoxFit.cover,
            type: TDImageType.circle,
          ),
          title: Row(
            children: [
              Text(data!['gift']['title']),
              const SizedBox(width: 10),
              TDTag(data!['type_name'], size: TDTagSize.small),
            ],
          ),
          subtitle: Text(DateTimeUtils.convertTimestampToDateString(data!['create_time']),
              style: const TextStyle(color: Colors.black38)),
          trailing: Text(data!['status_desc'],
              style: const TextStyle(color: Colors.black38)),
        ),
        const SizedBox(height: 25),
      ],
    );
  }
}

void main() {
  runApp(const MaterialApp(
    home: MyGift(),
  ));
}
